<?php

/**
 * CommentController
 *
 * @author yukio
 * @version $Id$
 */

require_once 'Zend/Controller/Action.php';
require_once 'Zend/Exception.php';
require_once 'Okute/Exception.php';
require_once 'Okute/Util/Data.php';

require_once APPLICATION_PATH . '/models/RequestModel.php';
require_once APPLICATION_PATH . '/models/CommentModel.php';
require_once APPLICATION_PATH . '/models/AclModel.php';

class CommentController extends Zend_Controller_Action
{
    /**
     * セッション管理用変数
     * @var Zend_Session_Namespace
     */
    private $_session;
    
    /**
     * アクセスコントロール
     * @var Zend_Acl
     */
    private $_acl;
    
    /**
     * リダイレクトヘルパー
     * @var Okute_Controller_Action_Helper_Redirector
     */
    private $_redirector;

    /**
     * Commentコントローラの初期化
     *
     * @return void
     */
    public function init() {
        $this->_session = new Zend_Session_Namespace('okute');
        $this->_acl = Zend_Registry::get('acl');
        $this->view->base = $this->getRequest()->getBaseUrl();

        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_REQUEST_COMMENT)) {
            throw new Okute_Exception('Access Control Error');
        }

        $this->_redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); 
    }

    /**
     * indexアクションはPOSTメソッドで入力されたコメントをデータベースに記録し、
     * 詳細画面へとリダイレクトする。
     *
     * @return void
     */
    public function indexAction() {
        if ($this->_session->userData === null) {
            throw new Okute_Exception('Session data "userData" is required');
        }

        if ($this->_session->displayId === null) {
            throw new Okute_Exception('Session data "displayId" is required');
        }

        if ($this->_session->userData['req_id'] === '') {
            throw new Okute_Exception('"userData" must have "req_id" entry');
        }

        $redirectUrl = $this->view->base.'/list/detail/id/' . $this->_session->displayId;        

        $paramPage = '';
        if ($this->_session->commentPage !== null) {
            $paramPage .= '/page/' . $this->_session->commentPage;
        }

        $val = $this->_getParam('comment');
        if ($val === '' || strlen($val) > 256) {
            $this->_redirector->redirectWithSession($redirectUrl);
        }

        $registerId = 'ななしさん';
        if ($this->_session->requester !== null) {
            $registerId = $this->_session->requester->requester_id;
        }
        if ($this->_session->party !== null) {
            $registerId = $this->_session->party->party_id;
        }
        if ($this->_session->operator !== null) {
            $registerId = $this->_session->operator;
        }

        $db = Zend_Registry::get('database', null);
        if ($db === null) {
            throw new Okute_Exception('Invalid registry "database"');
        }
        $db->beginTransaction();
        try {       
            $val = Okute_Util_Data::convertInputEncoding($val);
            $commentModel = new CommentModel();
            $commentModel->insert(array('req_id' => $this->_session->userData['req_id'],
                                        'create_datetime' => 'NOW()',
                                        'register_id' => $registerId,
                                        'comment' => $val,
                                        'enable' => 1));

            $select = $commentModel->select()->where('req_id = ?', $this->_session->reqId);
            $comments = Zend_Paginator::factory($select);
            $paramPage = '/page/' . $comments->getPageRange();

            $requestModel = new RequestModel();
            $where = $db->quoteInto('req_id = ?', $this->_session->userData['req_id']);
            $requestModel->update(array('request_note_count' => $comments->getTotalItemCount()), $where);
            $db->commit();
            
            $this->_redirector->redirectWithSession($redirectUrl . $paramPage);
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
    }

    public function enableAction()
    {
        if (!$this->_acl->isAllowed($this->_session->role, AclModel::RES_DISABLE_COMMENT)) {
            throw new Okute_Exception('Access Control Error');
        }
        
        $request = $this->getRequest();
        $id = $request->getParam('id');
        $enable = $request->getParam('enable');
        $datetime = $request->getParam('datetime');
        
        $commentModel = new CommentModel();
        $db = $commentModel->getAdapter();
        $where = array(
            $db->quoteInto('req_id = ?', $this->_session->reqId),
            $db->quoteInto('create_datetime = ?', $datetime)
        );
        $commentModel->update(array('enable' => $enable), $where);
        $paramPage = '';
        if ($this->_session->commentPage !== null) {
            $paramPage .= '/page/' . $this->_session->commentPage;
        }
        $redirectUrl = $this->view->base.'/list/detail/id/' . $this->_session->displayId;
        $this->_redirector->redirectWithSession($redirectUrl . $paramPage);
    }
}